// MineGame.cpp

#include "MineGame.h"
#include "MineNGUI.h"
#include <iostream>

/**
 * Constructor.
 */
MineGame::MineGame()
{
	mineGrid = new ObserverMineGrid( Size( 9, 9 ) );
	ui = new MineNGUI( mineGrid );
}

/**
* Constructor. Resizes the grid to the given size.
*/
MineGame::MineGame( const Size& size )
{
	mineGrid = new ObserverMineGrid( size );
	ui = new MineNGUI( mineGrid );
}

/**
 * Destructor.
 */
MineGame::~MineGame()
{
	delete ui;
	delete mineGrid;
}

/**
 * Starts the game!
 */
void MineGame::startGame()
{
	// Attach the UI to the ObserverMineGrid.
	mineGrid->attach( ui );

	// Action char...
	char userInput = 'a';

	// Print out the interface
	repaint();

	while( userInput != 'x' )
	{
		userInput = ui->getAction();

		Point p;

		switch( userInput )
		{
		// Sweep the mine. Get a point and send it forward.
		case 's':
			p = ui->getPoint();
			sweepMine( p );

			// The player hit a mine. Show info and reset the grid.
			if( mineGrid->isMine( p ) && !mineGrid->isFlagged( p ) )
			{
				// Quick and dirty
				std::cout << "You hit a mine!\n";
				reset();
			}
			// Check if the player finished the grid.
			else if( mineGrid->isDone() )
			{
				std::cout << "YOU DID IT!! :-)\n";
				reset();
			}

			break;
		// Flag the mine. Get a point and send it forward.
		case 'f':
			flagMine( ui->getPoint() );

			if( mineGrid->isDone() )
			{
				std::cout << "YOU DID IT!! :-)\n";
				reset();
			}

			break;
		// Reset the game.
		case 'r':
			reset();
			break;
		default:
			// No default action yet
			break;
		}
	}
}

/**
* Resets the clock and grid.
*/
void MineGame::reset()
{
	mineGrid->reset();
}

/**
 * Sweeps the mine (i.e. "a left click").
 *
 * @param p point to the mine to sweep
 */
void MineGame::sweepMine( const Point& p )
{
	mineGrid->sweepMine( p );
}

/**
 * Flags the mine (i.e. "a right click").
 *
 * @param p point to the mine to flag
 */
void MineGame::flagMine( const Point& p )
{
	mineGrid->flagMine( p );
}

/**
 * Repaints the UI.
 */
void MineGame::repaint()
{
	ui->printUI();
}
